package com.msmall.erp.sso.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.msmall.base.rms.service.RMSService;
import com.msmall.base.rms.util.RMSUtils;
import com.msmall.erp.base.Constant;
import com.msmall.erp.base.LoginConstant;
import com.msmall.erp.sso.vo.AdministerVO;

public class SecurityInterceptor implements HandlerInterceptor{

	@Autowired
	private RMSService rmsService;
	
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object arg2) throws Exception {
		HttpSession session = req.getSession(true);
		// 从session 里面获取用户名的信息
		AdministerVO vo = (AdministerVO) session.getAttribute(LoginConstant.HTTP_SESSION_KEY_ADMINISTER);
		if (vo == null || !vo.isLogin()) {
			res.sendRedirect("http://" + Constant.SITE_DOMAIN + Constant.SITE_DOMAIN_SSO_COMMON);
			return false;
		}else{
			String url = req.getServletPath();
			if(!"/mainMenu.do".equals(url)){
				if(!rmsService.checkUrlAuth(vo.getId(), url)){
					req.getRequestDispatcher("http://" + Constant.SITE_DOMAIN + Constant.SITE_RMS_AUTHERROR + RMSUtils.RMS_ERROR_PARAM + "=" + RMSUtils.RMS_ERROR_AUTH).forward(req, res);
				}
			}
		}
		return true;
	}
	
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}
	
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}


}
